<template>
  <div ref="chart" style="width: 100%; height: 100%" />
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'LineChart',
  props: {
    chartData: {
      type: Object,
      required: true
    },
    yAxisName: {
      type: String,
      default: ''
    },
    colors: {
      type: Array,
      default: () => ['#FFD700', '#32CD32']
    },
    seriesNames: {
      type: Array,
      default: () => ['系列1', '系列2']
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      const series = this.chartData.yData.map((data, index) => ({
        name: this.seriesNames[index],
        data: data,
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: this.colors[index],
          width: 2
        },
        itemStyle: {
          color: this.colors[index]
        },
        stack: 'total'
      }))

      const option = {
        grid: {
          top: 20,
          right: 10,
          bottom: 20,
          left: 40
        },
        xAxis: {
          type: 'category',
          data: this.chartData.xData,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          }
        },
        yAxis: {
          type: 'value',
          name: this.yAxisName,
          nameTextStyle: {
            padding: [0, 0, 0, 30],
            color: '#fff'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: 'rgba(255, 255, 255, 0.2)'
            }
          }
        },
        legend: {
          data: this.seriesNames,
          right: 10,
          top: 0,
          textStyle: {
            color: '#fff'
          }
        },
        series: series,
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontWeight: 'bold'
          },
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>'
            params.forEach((item) => {
              result += `${item.marker} ${item.seriesName}： <span style="float:right;font-weight:bold">${item.value}</span><br/>`
            })
            return result
          }
        }
      }
      this.chart.setOption(option)
    },
    handleResize() {
      this.chart && this.chart.resize()
    }
  }
}
</script>
